package cn.tedu.dimanage.message.webapi.config;


import cn.tedu.dimanage.message.webapi.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Classname: SecurityConfiguration
 * @Author: bromide
 * @CreateTime: 2022/6/25--12:45
 * @Version: V1.0
 * @Description:
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  // 开启通过注解配置权限
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    //@CrossOrigin
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用防跨域攻击
        http.csrf().disable();

        // URL 白名单
        String[] urls = {
                "/user/login",
                "/user/add-new",
                "/user/parse/jwt"
//                "/user/list/details",
        };

        // http://localhost:18090/user/login?username=username011&password=123456
        // 配置各请求路径的认证和授权
        http.authorizeRequests()// 请求需要授权才可以访问
//                .antMatchers(urls)  // 匹配一些路径
//                .permitAll()   // 允许直接访问(不需要经过认证和授权)
//                .anyRequest()  // 匹配除了以上配置的其他请求
//                .authenticated(); // 都需要认证
                .anyRequest()  // 匹配一些路径
                .permitAll();   // 允许直接访问(不需要经过认证和授权)

        // 注册处理JWT的过滤器
        // 此过滤器必须在Spring Security处理登陆的过滤器之前
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
